<template>
    <div>
        <div class="search">
            <input v-model="keyword" type="text" class="input" placeholder="请输入要搜索的城市">
        </div>
        <div class="search-content" ref="list" v-show="keyword">
            <ul>
                <li class="search-item border-bottom"
                    v-for="city of list"
                    :key="city.id"
                    @click="handleCityClick(city.name)"
                >
                    {{city.name}}
                </li>
                <li class="search-item border-bottom" v-show="hasNoData">没有找到匹配数据</li>
            </ul>
        </div>
    </div>
</template>

<script>
import BScroll from 'better-scroll'
import {mapActions} from 'vuex'

export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null,
      hasNoData: false
    }
  },
  methods: {
    handleCityClick (cityName) {
      this.cityChange(cityName)
      this.$router.push('/')
    },
    ...mapActions(['cityChange'])
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }

      this.timer = setTimeout(() => {
        const result = []
        for (let item in this.cities) {
          this.cities[item].forEach((city) => {
            if (city.name.indexOf(this.keyword) > -1 || city.spell.indexOf(this.keyword) > -1) {
              result.push(city)
            }
          })
        }
        this.list = result
        if (!this.list.length) {
          this.hasNoData = true
        } else {
          this.hasNoData = false
        }
      }, 100)
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.list)
  }
}
</script>

<style lang="stylus" scoped>
@import "~styles/varibles.styl"
.search
    height .72rem
    padding 0 .1rem
    background-color $bgcolor
    .input
        box-sizing border-box
        height .62rem
        width 100%
        line-height .62rem
        text-align center
        padding 0 .1rem
        border-radius .06rem
        color #666
.search-content
    z-index 1
    position absolute
    overflow hidden
    top 1.58rem
    left 0
    right 0
    bottom 0
    background-color #eee
    .search-item
        padding .2rem
        background-color #fff
        color #666
</style>
